package com.example.test427;

import android.content.Context;
import android.os.Build;
import android.print.PrintManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

/**
 * @author jie
 * @date 2021/4/27 -10:56
 */
public class WebAppInterface {
    Context mContext;
    WebView view;

    /**
     * Instantiate the interface and set the context
     */
    WebAppInterface(Context c) {
        mContext = c;
    }

    WebAppInterface(Context c, WebView webView) {
        mContext = c;
        this.view = webView;
    }

    /**
     * Show a toast from the web page
     */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @JavascriptInterface
    public void doPrint() {
        createWebPrintJob(view);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void createWebPrintJob(WebView webView) {

        PrintManager printManager = (PrintManager) mContext
                .getSystemService(Context.PRINT_SERVICE);

        String jobName = mContext.getString(R.string.app_name) + " Document";

        printManager.print(jobName, new MyPrintDocumentAdapter(mContext), null);
    }

}

